#include "mainwindow.h"
#include "qcustomplot.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QString>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
     ui->setupUi(this);
     foreach( const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
     {
         ui->serialPortComboBox->addItem(info.portName());
         qDebug()<<"serial port search finished";
     }
    // ui->rateComboBox->addItem("9600");
    // ui->rateComboBox->addItem("19200");
     //ui->rateComboBox->addItem("115200");
   ui->rateComboBox->insertItem(0,"9600");
   ui->rateComboBox->insertItem(1,"19200");
   ui->rateComboBox->insertItem(2,"115200");
     graph_init();
     //qDebug()<<"Main thread: " <<QThread::currentThreadId();
     m_uart.moveToThread(&m_qthread);
     m_qthread.start();
}

MainWindow::~MainWindow()
{
    m_qthread.quit();
    m_qthread.wait();
    //delete mTag1;
    //delete mTag2;
    delete ui;
}

void MainWindow::graph_init()
{
    QLinearGradient plotGradient;
    plotGradient.setColorAt(0,QColor(80,80,80));
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom |
                                QCP::iSelectAxes | QCP::iSelectLegend |
                                QCP::iSelectPlottables);
    ui->widget->xAxis->setLabelColor(Qt::blue);
    ui->widget->yAxis->setLabelColor(Qt::white);
    ui->widget->yAxis2->setLabelColor(Qt::blue);
    ui->widget->xAxis->setTickLabelColor(Qt::white);
    ui->widget->yAxis->setTickLabelColor(Qt::white);
    ui->widget->yAxis2->setTickLabelColor(Qt::white);

    ui->widget->xAxis->setBasePen(QPen(Qt::blue, 1)); //坐标轴颜色及宽度
    ui->widget->yAxis->setBasePen(QPen(Qt::white, 1));
    ui->widget->yAxis2->setBasePen(QPen(Qt::blue, 1));
    ui->widget->xAxis->setTickPen(QPen(Qt::red, 1)); //主刻度
    ui->widget->yAxis->setTickPen(QPen(Qt::white, 1));
    ui->widget->yAxis2->setTickPen(QPen(Qt::red, 1));
    ui->widget->xAxis->setSubTickPen(QPen(Qt::white, 1)); //副刻度
    ui->widget->yAxis->setSubTickPen(QPen(Qt::white, 1));
    ui->widget->yAxis2->setSubTickPen(QPen(Qt::white, 1));

    ui->widget->xAxis->setLabel("time/ms"); // x轴的文字
    ui->widget->yAxis2->setLabel("voltage");    // y轴的文字

    // configure plot to have two right axes:
    ui->widget->yAxis->setTickLabels(false);

    connect(ui->widget->yAxis2,
            SIGNAL(rangeChanged(QCPRange)),
            ui->widget->yAxis,
            SLOT(setRange(QCPRange))); // left axis only mirrors inner right axis
    ui->widget->xAxis->setVisible(true);
    ui->widget->yAxis2->setVisible(true);

    ui->widget->axisRect()->addAxis(QCPAxis::atRight);
    ui->widget->axisRect()
        ->axis(QCPAxis::atRight, 0)
        ->setPadding(30); // add some padding to have space for tags
    ui->widget->axisRect()
        ->axis(QCPAxis::atRight, 1)
       ->setPadding(30); // add some padding to have space for tags

    mGraph1 = ui->widget->addGraph(
        ui->widget->xAxis, ui->widget->axisRect()->axis(QCPAxis::atRight, 1));
    mGraph2 = ui->widget->addGraph(
        ui->widget->xAxis, ui->widget->axisRect()->axis(QCPAxis::atRight,0));
    mGraph1->setPen(QPen(QColor(250, 120, 0)));
    mGraph2->setPen(QPen(QColor(0, 180, 60)));

    //mTag1 = new AxisTag(mGraph1->valueAxis());
    //mTag1->setPen(mGraph1->pen());
    //mTag2 = new AxisTag(mGraph2->valueAxis());
    //mTag2->setPen(mGraph2->pen());
    connect(&mDataTimer, SIGNAL(timeout()), this, SLOT(timer_slot()));
    mDataTimer.start(500);

}
extern double frequency_extern;
extern QByteArray rx_input ;
void MainWindow::graph_update()
{
    double a = frequency_extern;
    a =  a * 33;
    a = a / 4096;
    if( (a <= 0)||(a > 33 ))
        return;
    // calculate and add a new data point to each graph:
    mGraph1->addData(mGraph1->dataCount(), a);
    mGraph2->addData(mGraph2->dataCount(), 0);

    // make key axis range scroll with the data:
    ui->widget->xAxis->rescale();
    ui->widget->yAxis2->rescale();
    mGraph1->rescaleValueAxis(true, true);
   // mGraph2->rescaleValueAxis(true, true);
    ui->widget->xAxis->setRange(
        ui->widget->xAxis->range().upper, 100, Qt::AlignRight);

    // update the vertical axis tag positions and texts to match the rightmost
    // data point of the graphs:
    double graph1Value = mGraph1->dataMainValue(mGraph1->dataCount() - 1);
    double graph2Value = mGraph2->dataMainValue(mGraph2->dataCount() - 1);

    ui->widget->replot();
   //QString rx_buf_tmp =  QString::fromLocal8Bit(rx_input);
    QString rx_buf= m_uart.getRxString();
    if(!rx_buf.isEmpty())
    {
       ui->rx_buf->insertPlainText(rx_buf); //追加显示，末尾不会添加
       m_uart.clrRxString();
     }
}

void MainWindow::timer_slot() { graph_update(); }


void MainWindow::on_open_port_clicked()
{
    if(this->ui->open_port->text() == QObject::tr("打开串口") )
    {
        m_uart.getSerialPort()->setPortName(ui->serialPortComboBox->currentText());
        m_uart.getSerialPort()->setBaudRate(ui->rateComboBox->currentText().toInt());
        m_uart.getSerialPort()->setDataBits(QSerialPort::Data8);
        m_uart.getSerialPort()->setParity(QSerialPort::NoParity);
        m_uart.getSerialPort()->setStopBits(QSerialPort::OneStop);
        m_uart.getSerialPort()->setFlowControl(QSerialPort::NoFlowControl);
        if(!m_uart.getSerialPort()->open(QIODevice::ReadWrite))
        {
           // QMessageBox::Critial(NULL,"提示"，"open failed");
            qDebug()<<"open failed";
            return;
        }
        else
        {

           qDebug()<<"uart successful";

        }
        this->ui->open_port->setText( QObject::tr("关闭串口") );
    }
    else
    {
       m_uart.getSerialPort()->close();
        this->ui->open_port->setText(QObject::tr("打开串口") );

    }


}
